package drds.data_propagate.driver;

import drds.data_propagate.driver.packets.client.command_packet.QueryPacket;
import drds.data_propagate.driver.packets.server.ErrorPacket;
import drds.data_propagate.driver.packets.server.OkPacket;
import drds.data_propagate.driver.utils.PacketManager;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 默认输出的数据编码为UTF-8，如有需要请正确转码
 */
public class UpdateExecutor {

    private static final Logger logger = LoggerFactory.getLogger(UpdateExecutor.class);
    @Setter
    @Getter
    private Connector connector;

    public UpdateExecutor(Connector connector) throws IOException {
        if (!connector.isConnected()) {
            throw new IOException("should execute connector.connect() first");
        }

        this.connector = connector;
    }

    public OkPacket update(String updateString) throws IOException {
        QueryPacket queryPacket = new QueryPacket();
        queryPacket.setQueryString(updateString);
        byte[] bodyBytes = queryPacket.encode();
        PacketManager.writeBodyBytes(connector.getSocketChannel(), bodyBytes);
        //
        byte[] packetBodyBytes = PacketManager.readBytes(connector.getSocketChannel(),
                PacketManager.readHeader(connector.getSocketChannel(), 4).getPacketBodyLength());
        if (packetBodyBytes[0] < 0) {
            ErrorPacket errorPacket = new ErrorPacket();
            errorPacket.decode(packetBodyBytes);
            throw new IOException(errorPacket + "\n with command: " + updateString);
        }
        //
        OkPacket okPacket = new OkPacket();
        okPacket.decode(packetBodyBytes);
        return okPacket;
    }
}
